package com.xinqi.common.base.error.exception;

import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.base.error.ErrorDetail;
import com.xinqi.common.base.response.R;

/**
 * 响应异常
 *
 * @author linkai
 * @date 2022/11/25
 */
public class ErrorResponseException extends RuntimeException {

    private final ErrorDetail detail;

    public ErrorResponseException() {
        this(CommonErrors.INTERNAL_SERVER_ERROR);
    }

    public ErrorResponseException(ErrorDetail detail) {
        super(detail.getMsg());
        this.detail = detail;
    }

    public ErrorResponseException(ErrorDetail detail, Throwable cause) {
        super(detail.getMsg(), cause);
        this.detail = detail;
    }

    @Deprecated
    public static ErrorResponseException of(Integer code, String message) {
        return new ErrorResponseException(ErrorDetail.with(code, message));
    }

    public ErrorDetail getDetail() {
        return detail;
    }

    public <T> R<T> getResult() {
        int code = detail.getCode();
        if (code == 0) {
            code = CommonErrors.BAD_REQUEST.getCode();
        }
        return R.error(code, detail.getMsg(), detail.getPath());
    }
}
